package de.wojenko.sps;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.itextpdf.text.DocumentException;

public abstract class AbstractPDFBacklogItemListExporter {
	private static final Logger log = LoggerFactory
			.getLogger(AbstractPDFBacklogItemListExporter.class);

	private final CardType cardType;
	private final String description;

	public AbstractPDFBacklogItemListExporter(CardType cardType,
			String description) {
		super();
		this.cardType = cardType;
		this.description = description;
	}

	public void exportSprint(File arg0, SprintData<XmlUserStory> arg1) {
		try {
			createPDF(arg0, arg1);
		} catch (FileNotFoundException | DocumentException e) {
			log.error("Exception during PDF Creation", e);
		}
	}

	public String getDescription() {
		return description;
	}

	public void createPDF(File arg0, List<PDFCard> cards)
			throws FileNotFoundException, DocumentException {
		try (LandscapeDinA5PDFCardDocument document = new LandscapeDinA5PDFCardDocument(
				arg0, cardType)) {
			for (PDFCard pdfCard : cards) {
				document.addCard(pdfCard);
			}
		}
	}

	public void createPDF(File arg0, SprintData<XmlUserStory> arg1)
			throws DocumentException, FileNotFoundException {

		List<PDFCard> cards = Lists.newArrayList();
		// build an array of cards
		for (XmlUserStory userStory : arg1.getBacklogItemList()) {
			int i = 1;
			for (XmlBacklogItemArtefact artefact : getArtefacts(userStory)) {
				PDFCard card = new PDFCard();
				card.header = userStory.getId() + " / "
						+ String.format("%02d", i);
				card.text = artefact.getText();
				card.comment = artefact.getComment();
				cards.add(card);
				i++;
			}
		}
		createPDF(arg0, cards);
	}

	protected abstract List<XmlBacklogItemArtefact> getArtefacts(XmlUserStory userStory);
}